import { ErrorType, CodeType, ChatType, LiveType } from './ChatUtils';
import conf from './Api';
import WebsocketHeartbeatJs from './WebsocketHeartbeatJs';
import * as DateUtil from '../commons/DateUtil'

class RequestUtils {
  constructor() {
    this.instance = null;
    this.isRefreshing = false;
    this.subscribers = [];
  }

  /**
   * 单例构造方法，构造一个广为人知的接口，供用户对该类进行实例化
   * @returns {RequestUtils}
   */
  static getInstance() {
    if (!this.instance) {
      this.instance = new RequestUtils();
    }
    return this.instance;
  }

  /**
   * 连接超时函数
   * @param fetchPromise
   * @param timeout
   * @returns {Promise<unknown>}
   */
  timeoutFetch(fetchPromise, timeout) {
    let abortFn = null;

    //这是一个可以被reject的promise
    let abortPromise = new Promise(function(resolve, reject) {
      abortFn = function() {
        reject(ErrorType.TIMEOUT_ERROR);
      };
    });

    //这里使用Promise.race，以最快 resolve 或 reject 的结果来传入后续绑定的回调
    let abortAblePromise = Promise.race([fetchPromise, abortPromise]);

    setTimeout(function() {
      abortFn();
    }, timeout);

    return abortAblePromise;
  }

  /**
   * websocket 连接处理
   * @param self vue
   */
  webSocketOperation(self) {
    let websocketHeartbeatJs = new WebsocketHeartbeatJs({
      url: conf.getWsUrl()
    });

    websocketHeartbeatJs.onopen = function() {
      websocketHeartbeatJs.send('{"code":' + CodeType.CODE_READY + '}');
    };

    websocketHeartbeatJs.onmessage = function(event) {
      let data = event.data;
      let sendInfo = JSON.parse(data);

      // 真正的消息类型
      if (sendInfo.code === CodeType.CODE_MESSAGE) {
        let message = sendInfo.message;

        message.timestamp = DateUtil.formatDateTime(new Date(message.timestamp));
        // 接受到的消息不是本人发送, 则添加消息
        if (String(message.username) !== self.$store.state.username) {
          self.$store.commit('addMessage', message);
        }

        // 接收到系统消息
        if (String(message.type) === ChatType.MSG_SYSTEM) {
          // 直播开始通知
          if (String(message.username) === LiveType.LIVE_START) {
            self.$store.commit('setLiving', true)
          }
          // 直播结束通知
          if (String(message.username) === LiveType.LIVE_STOP) {
            self.$store.commit('setLiving', false)
          }
        }
      }
    };

    // 重连事件
    websocketHeartbeatJs.onreconnect = function() {
      console.log('reconnecting...');
    };

    // 连接错误
    let count = 0;
    websocketHeartbeatJs.onerror = function(error) {
      console.log("connect error");
    };

    // 存储Websocket
    self.$store.commit('setWebsocket', websocketHeartbeatJs);
  }
}

export default RequestUtils;
